package com.wthink.hzgj.data.repository

import com.wthink.hzgj.data.BusDataBase
import com.wthink.hzgj.data.SettingRepository
import com.wthink.hzgj.data.domain.Setting
import com.wthink.hzgj.data.domain.SettingKey
import java.util.concurrent.ConcurrentHashMap

object SettingWithCacheRepository : SettingRepository {
    private val cache = ConcurrentHashMap<String, String>()
    private val settingDao = BusDataBase.getInstance().settingDao()

    init {
        cache.put(SettingKey.LINE, "")//线路
        cache.put(SettingKey.USER, "")//用户
    }

    override suspend fun findSetting(key: String): String? {
        val value = cache[key]
        if (value != null) {
            return value
        }

        val ret = settingDao.findByKey(key)?.value
        if (ret != null) {
            cache.put(key, ret)
        }
        return ret
    }

    override suspend fun saveSetting(key: String, value: String) {
        cache.put(key, value)
        settingDao.save(Setting(0, key, value))
    }
}